"""
扣子智能体调用
coze平台对话相关的三个API，通过顺序发起对话->查看对话详情->查看对话消息详情三个API，就可以在客户端远程调用一次智能体服务。
"""
import requests
import json,time

# 个人访问令牌
personal_access_token = ""      # 填写你的扣子 API访问令牌
# 你的botID
bot_id = ""  # 请填写你创建的中小学全科学习扣子智能体ID
baseUrl =  'https://api.coze.cn/v3/chat'
# 构建请求头
headers = {
    "Authorization": f"Bearer {personal_access_token}",
    'Content-Type': 'application/json'  # # 请求的内容类型
}

# 处理应答数据的函数
def processQuestionAnswer(response_data):
    if response_data['code']:   # 如果返回码不为0，表示应答异常
        print("应答异常：", response_data['msg'])
    else:
        data = response_data['data']    
        count = 0                       
        for item in data:               
            if item['type'] == 'answer' and item['content_type'] == 'text':
            # 如果是智能体的应答，有可能有多个满足字典元素['type'] == 'answer'
            
                print("智能体应答：", item['content'])
                return item['content']
            elif item['type'] == 'follow_up':           # 如果是需要用户跟进的问题
                if count == 0:
                    print("您可以参考如下方式提问：")
                print(f"☆ 问题{count + 1}：", item['content'])     # 打印跟进问题
                count += 1

# 获取问答数据的函数
def getQuesyionAnswer(conversationID, chatID):
    params = {"bot_id": bot_id, "task_id": chatID}      
    getChatStatusUrl = baseUrl + f'/retrieve?conversation_id={conversationID}&chat_id={chatID}&'    

    while True:
        
        response = requests.get(getChatStatusUrl, headers=headers, params=None)     
       
        if response.status_code == 200:     
            response_data = response.json() 
            print(f"response_data:\n{json.dumps(response_data, indent=4, ensure_ascii=False)}")     
            status = response_data['data']['status']    
            if status == 'completed':   
                
                getChatAnswerUrl = baseUrl + f'/message/list?chat_id={chatID}&conversation_id={conversationID}'
                response = requests.get(getChatAnswerUrl, headers=headers, params=params)   
                if response.status_code == 200:
                    response_data = response.json()     
                    print("模型返回数据:\n", json.dumps(response_data, indent=4, ensure_ascii=False))     

                    questionAnswer = processQuestionAnswer(response_data)         
                    return questionAnswer
                break
            else:
                print(f"任务仍在处理中，状态: {status}")
                time.sleep(3)  # 等待3秒后再次检查
        else:
            print(f"请求失败，状态码: {response.status_code}")
            break
    return False

# 发送问题并获取应答的函数
def questionService(questionText):
    # 定义请求消息体，API的URL和授权令牌
    questionText = questionText + '请使用纯文本方式回复。'
    data = {
        "bot_id": bot_id,
        "user_id": "jiangwp",
        "stream": False,
        "auto_save_history": True,
        "additional_messages": [
            {
                "role": "user",
                "content": questionText,
                "content_type": "text"
            }
        ]
    }

    # 发送POST请求
    #print(f"请求信息:{json.dumps(data, indent=4, ensure_ascii=False)}")             # 打印请求信息
    response = requests.post(baseUrl, headers=headers, data=json.dumps(data))       # 发送POST请求
    
    # 检查响应状态码
    if response.status_code == 200:        
        response_data = response.json()        
        print("响应内容:", json.dumps(response_data, indent=4, ensure_ascii=False))     # 打印响应内容
        chatid = response_data['data']['id']        # 获取聊天ID
        answer = response_data.get("answer")        # 尝试获取即时应答（如果有）
        conversation_id = response_data['data']['conversation_id']      # 获取会话ID
        print(f"chatid={chatid},智能体应答: {answer}")                       # 打印聊天ID和即时应答（如果有）

        an = getQuesyionAnswer(conversation_id, chatid)      # 获取完整的问答数据
        return an

    else:
        print("请求失败，状态码:", response.status_code)
        print("错误信息:", response.text)



if __name__ == '__main__':
    an = questionService("我是刚入学的初一学生，学好初中级物理需要从哪些方面入手？")
    print(an)

